/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-08 23:07:47
 * @LastEditTime: 2022-05-16 11:01:39
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 
 */
import React, { Fragment, useState } from 'react'
import {useNavigate} from 'react-router-dom'

import { Button, Table, Modal, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons';


import Dayjs from 'dayjs'

import { getList, deleteArticle } from '@/api/list'
import './index.less'

export default function List() {
	const navigate = useNavigate()
	const [dataSource, setDataSource] = useState([])
	const [pagination, setPagination] = useState({ current: 1, pageSize: 1, total: 0 })
	const formatDataSource = (arr = []) => {
		return arr.map(item => {
			item.date = Dayjs(item.date).format('YYYY-MM-DD HH:mm:ss')
			item.newTitle = <NewTitle title={item.title} subTitle={item.subTitle} />
			return item
		})
	}
	const initList = (pagination) => {
		getList(pagination).then(({ data }) => {
			setDataSource(formatDataSource(data.arr))
			setPagination({
				current: data.num,
				pageSize: data.count,
				total: data.total
			})
		})

	}
	React.useEffect(() => {
		initList({ num: 0, count: 10 })
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [])

	const handleChange = ({ current, pageSize }) => {
		initList({ num: current, count: pageSize })
	}

	const columns = [
		{
			dataIndex: 'newTitle',
			render: (el) => <Fragment>{el}</Fragment>,
			width: '70%'
		}
		,
		{
			dataIndex: 'date',
		},
		{
			dataIndex: '',
			render: ({id}) => {
				return (
					<div>
						<Button type='primary' ghost style={{ marginRight: '10px' }} onClick={()=>navigate(`/edit?id=${id}`)}>编辑</Button>
						<Button type='danger' ghost onClick={() => handleDeleteArticle(id)}>删除</Button>
					</div>
				)
			},
		},
	];

	const { confirm } = Modal;
	const handleDeleteArticle = (id) => {
		confirm({
			title: `您确认删除文章【${id}】吗?`,
			icon: <ExclamationCircleOutlined />,
			okText: '确认',
			cancelText: '取消',
			async onOk() {
				const { message: msg } = await deleteArticle({ id })
				message.success(msg)
				initList({ num: 0, count: 10 })
			}
		})
	}
	return (
		<div className='table-container'>
			<Table showHeader={false} dataSource={dataSource} columns={columns} pagination={pagination} rowKey={record => record.id} onChange={handleChange} />
		</div>
	)
}

function NewTitle(props) {
	return (
		<div>
			<a href="123" className='title'>{props.title}</a>
			<span className='subTitle'>{props.subTitle}</span>
		</div>
	)
}
